package com.liuwei.protocol;

import com.liuwei.common.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

// 消费者客户端，使用它开启网络网络调用，并且把IOUtils的结果打印出来
public class HttpClient {
    public String send (String hostname, Integer port, Invocation invocation) throws IOException {
       try {
           URL url = new URL("http",hostname,port,"/");
           HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
           httpURLConnection.setRequestMethod("POST");
           httpURLConnection.setDoOutput(true);

           OutputStream outputStream = httpURLConnection.getOutputStream();
           ObjectOutputStream oos = new ObjectOutputStream(outputStream);
           oos.writeObject(invocation);
           oos.flush();
           oos.close();

           InputStream inputStream = httpURLConnection.getInputStream();
           String result = IOUtils.toString(inputStream);
           return result;
       } catch (MalformedURLException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw e;
       }
    }

}
